package com.siwei.mes.sync.erp;

import com.alibaba.fastjson.JSON;
import com.siwei.mes.common.annotation.AnonymousAccess;
import com.siwei.mes.common.base.BaseParams;
import com.siwei.mes.common.result.ApiResult;
import com.siwei.mes.common.result.Json;
import com.siwei.mes.common.validator.bus.SyncGroup;
import com.siwei.mes.sync.erp.entity.SyncErpWaybill;
import com.siwei.mes.sync.erp.service.SyncErpWaybillService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import static com.siwei.mes.common.exception.handler.MessageHandler.assertTrue;

/**
 * 同步ERP运单
 *
 * @Description: 同步ERP运单
 * @Version: 1.0
 * @author: mlchen
 * @date: 2024/8/21 22:12
 */
@Api(value = "同步ERP运单")
@RestController
@RequestMapping("erp/waybill")
public class SyncErpWaybillController {
    private static final Logger log = LoggerFactory.getLogger("erp");
    @Value("${erp-token}")
    private String ERP_TOKEN;
    @Resource
    private SyncErpWaybillService syncErpWaybillService;


    /**
     * 校验token
     *
     * @param request
     */
    public void checkToken(HttpServletRequest request) {
        String token = request.getHeader(BaseParams.Authorization);
        assertTrue(StringUtils.isBlank(token), "授权token为空");
        assertTrue(!token.equals(ERP_TOKEN), "token不正确");
    }

    @AnonymousAccess
    @ApiOperation(value = "新增或修改运单")
    @PostMapping("/saveOrUpdate")
    public Json saveOrUpdate(@RequestBody @Validated(SyncGroup.class) SyncErpWaybill syncInfo, HttpServletRequest request) {
        log.info("ERP新增或修改运单，入参：{}", JSON.toJSONString(syncInfo));
        this.checkToken(request);
        try {
            syncErpWaybillService.saveOrUpdate(syncInfo);
        } catch (Exception e) {
            log.error("ERP新增或修改运单失败，错误原因：【{}】", e.getMessage(), e);
            /**手动回滚事务*/
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            assertTrue("ERP新增或修改运单，错误原因：" + e.getMessage() + "】");
        }
        return Json.succ().data(new ApiResult());
    }
}
